
import pymysql.cursors
import logging
import uuid
import json as j
import system_setup
from flask import request,jsonify
from uirls import time_uirls
from data_analysis import data_subscription
from device_info import update_device_currentState
from configparser import ConfigParser
from threading import Thread,Lock
from uirls import web_socket
# 读取配置文件
conf = ConfigParser()
conf.read("setting.ini",encoding='utf-8')
# 互斥锁
mutex = Lock()
# log日志
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 数据库连接
def mysql():
    mydb = pymysql.connect(
        host=conf.get("mysql_settings","host"),
        port=int(conf.get("mysql_settings","port")),
        user=conf.get("mysql_settings","user"),
        password=conf.get("mysql_settings","password"),
        database='data_info',
        cursorclass=pymysql.cursors.DictCursor
    )
    return mydb
# 正常数据新增
def add(jsons):
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        number = jsons['number']
        type = jsons['type']
        for paramInfo in jsons['paramInfo']:

            if paramInfo['name'] == '水压':
                jsons['water_pressure'] = paramInfo['value']
            elif paramInfo['name'] == '当前水位':
                jsons['water_level'] = paramInfo['value']
        water_pressure = jsons['water_pressure'] if jsons.get("water_pressure") is not None else ""
        water_level = jsons['water_level'] if jsons.get("water_level") is not None else ""
        data_time = jsons['time']
        id = str(uuid.uuid4())
        sql = ""
        if type == 'water':
            sql = "insert into device_normal_log_fire_water (id,number,water_pressure,water_level,data_time) values('%s','%s','%s','%s','%s')" \
                  %(id,number,water_pressure,water_level,data_time)
            insert = cursor.execute(sql)
        mydb.commit()
        jsonParam = {"number": number,"time": data_time,"currentState": "1"}
        # 更新设备状态
        update_device_currentState(jsonParam)
        # 第三方消息订阅http
        data_subscription.data(jsons)
        # 第三方消息订阅mqtt
        data_subscription.mqtt_data(jsons)
        # ws
        web_socket.send(str(jsons).replace("'",'"'))
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭数据库
    return jsonify(
        msg = "success",
        code = 0
    )
# 获取今日、当月消息量
def all_data_day_month_count():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = j.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg = token['msg'],
            code = 1
        )
    elif token['code'] == 401:
        return jsonify(
            msg = token['msg'],
            code = token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        sql = "select COUNT(date_time) as count from all_data where TO_DAYS(date_time) = TO_DAYS(now())"
        mutex.acquire()
        cursor.execute(sql)
        mutex.release()
        dayCount = cursor.fetchone()
        cursor = mydb.cursor()
        sql = "SELECT COUNT(date_time) as count FROM all_data WHERE DATE_FORMAT(date_time, '%Y%m' ) = DATE_FORMAT(CURDATE( ) , '%Y%m' )"
        cursor.execute(sql)
        monthCount = cursor.fetchone()
        json_data = {}
        json_data['dayCount'] = dayCount['count']
        json_data['monthCount'] = monthCount['count']
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=json_data
    )
# 统计设备消息量（折线图）
def all_data_count():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = j.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg = token['msg'],
            code = 1
        )
    elif token['code'] == 401:
        return jsonify(
            msg = token['msg'],
            code = token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        # 开始时间
        startTime = jsons['startTime']
        # 结束时间
        endTime = jsons['endTime']
        sql = "SELECT date_time FROM all_data WHERE date_time BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY date_time DESC"
        cursor.execute(sql)
        cur_data = cursor.fetchall()
        return_data = []
        if jsons.__contains__('type'):
            if jsons['type'] == '天':
                hours = time_uirls.getHour(endTime[11:13])
                for hour in hours:
                    count = 0
                    json = {}
                    for data in cur_data:
                        date_time = str(data['date_time'])
                        if date_time[11:13] == hour:
                            count = count+1
                    json[hour] = count
                    return_data.append(json)
            elif jsons['type'] == '周':
                days = time_uirls.getDay(7,endTime)
                for day in days:
                    count = 0
                    json = {}
                    for data in cur_data:
                        date_time = str(data['date_time'])
                        if date_time[5:10] == day:
                            count = count+1
                    json[day] = count
                    return_data.append(json)
            elif jsons['type'] == '月':
                days = time_uirls.getDay(30,endTime)
                for day in days:
                    count = 0
                    json = {}
                    for data in cur_data:
                        date_time = str(data['date_time'])
                        if date_time[5:10] == day:
                            count = count+1
                    json[day] = count
                    return_data.append(json)
            elif jsons['type'] == '年':
                months = time_uirls.getMonths(endTime)
                for month in months:
                    count = 0
                    json = {}
                    for data in cur_data:
                        date_time = str(data['date_time'])
                        if date_time[:7] == month:
                            count = count+1
                    json[month] = count
                    return_data.append(json)
        else:
            startTime1,startTime2 = startTime.split(' ')
            endTime1,endTime2 = endTime.split(' ')
            if startTime1 == endTime1:
                hours = time_uirls.getHour(endTime[11:13])
                for hour in hours:
                    count = 0
                    json = {}
                    for data in cur_data:
                        date_time = str(data['date_time'])
                        if date_time[11:13] == hour:
                            count = count+1
                    json[hour] = count
                    return_data.append(json)
            else:
                days = time_uirls.getDays(startTime1,endTime1)
                for day in days:
                    count = 0
                    json = {}
                    for data in cur_data:
                        date_time = str(data['date_time'])
                        if date_time[:10] == day:
                            count = count+1
                    json[day] = count
                    return_data.append(json)
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=return_data
    )

